﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Xml;
using System.Text;
using System.Xml.Linq;
using System.Data;
using System.Net;
using System.Web.Script.Serialization;
using Cms.Common;
using Senparc.Weixin.MP.Entities;
using System.Collections;
public partial class wx_index : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        
        if (!IsPostBack)
        {

            string poststr = "";
            setlog("IsPostBack", "IsPostBack");
            HttpContext.Current.Response.ContentType = "text/xml";
            if (HttpContext.Current.Request.HttpMethod.ToLower() == "post")
            {
                setlog("IsPostBack", "post");
                Stream s = System.Web.HttpContext.Current.Request.InputStream;
                byte[] b = new byte[s.Length];
                s.Read(b, 0, (int)s.Length);
                poststr = Encoding.UTF8.GetString(b);
                wxuser.setstatistics("", "2", poststr, 1, 1);
                HttpContext.Current.Response.ContentType = "text/xml";
                //writelog(poststr);

                info(poststr);
            }
            else
            {
                setlog("IsPostBack", "get");
                InterfaceTest();
            }
        }
    }


    #region 添加日志
    public void setlog(string str, string sname)
    {
        Cms.BLL.C_admin_log cm = new Cms.BLL.C_admin_log();
        Cms.Model.C_admin_log mc = new Cms.Model.C_admin_log();
        mc.remark = str;
        mc.action_type = "微信信息";
        mc.user_name = sname;
        mc.add_time = DateTime.Now;
        cm.Add(mc);
    }
    #endregion

    #region 服务器接受================================
    public void info(string poststr)
    {
        try
        {
            setlog("服务器接受", "服务器接受");
            wxuser.setstatistics("", "微信消息", poststr, 1, 1);
            string res = "";

            #region  //地图location================================
            if (poststr.IndexOf("location") > -1 || poststr.IndexOf("LOCATION") > -1)
            {
                wxmessage wx = new wxmessage();//声明
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(poststr);
                XmlElement root = xml.DocumentElement;


                wx.ToUserName = root.SelectSingleNode("ToUserName").InnerText;
                wx.FromUserName = root.SelectSingleNode("FromUserName").InnerText;
                wx.MsgType = root.SelectSingleNode("MsgType").InnerText;
                //if (wx.MsgType.Trim() == "text")
                //{
                //    wx.Content = root.SelectSingleNode("Content").InnerText;
                //}
                //if (wx.MsgType.Trim() == "event")
                //{
                //    wx.EventName = root.SelectSingleNode("Event").InnerText;
                //    wx.EventKey = root.SelectSingleNode("EventKey").InnerText;
                //}
                //if (wx.MsgType.Trim() == "voice")
                //{
                //    wx.Recognition = root.SelectSingleNode("Recognition").InnerText;
                //}
                if (wx.MsgType.Trim() == "location")
                {
                    wx.Location_X = root.SelectSingleNode("Location_X").InnerText;
                    wx.Location_Y = root.SelectSingleNode("Location_Y").InnerText;
                    wx.Scale = root.SelectSingleNode("Scale").InnerText;
                    wx.MsgId = root.SelectSingleNode("MsgId").InnerText;
                    wx.Label = root.SelectSingleNode("Label").InnerText;
                }


                StringBuilder sb = new StringBuilder();
                Cms.BLL.sc_stores sc = new Cms.BLL.sc_stores();
                DataTable dtsc = sc.GetList("isHidden=0").Tables[0];

                int i = 0;
                foreach (DataRow dr in dtsc.Rows)
                {
                    double d_Location_X = double.Parse(wx.Location_X);
                    double d_Location_Y = double.Parse(wx.Location_Y);
                    double d2_Location_X = double.Parse(dr["latitude"].ToString());
                    double d2_Location_Y = double.Parse(dr["longitude"].ToString());
                    double cd = getcalculate(d_Location_X, d_Location_Y, d2_Location_X, d2_Location_Y);

                    if (cd > double.Parse("0"))
                    {
                        i++;
                        sb.Append("<item>");
                        sb.Append("<Title><![CDATA[" + dr["storename"].ToString() + ":距离该门店大约" + cd.ToString("0.00") + "米]]></Title> ");
                        sb.Append("<Description><![CDATA[距离该门店大约" + cd.ToString("0.00") + "米]]></Description>");
                        sb.Append("<PicUrl><![CDATA[" + dr["picurl"].ToString() + "]]></PicUrl>");
                        sb.Append("<Url><![CDATA[" + dr["linkurl"].ToString() + "]]></Url>");
                        sb.Append("</item>");
                    }
                    if (i == 10)
                    {
                        break;
                    }
                }
                if (sb.Length > 0)
                {

                    res = sendPicMessage(wx, sb.ToString(), i);

                }
                else
                {
                    res = sendTextMessage(wx, "暂无任何门店消息！");
                }


            }
            #endregion

            #region //关注=======================
            if (poststr.IndexOf("subscribe") > -1 || poststr.IndexOf("SUBSCRIBE") > -1)
            {
                wxmessage wx = new wxmessage();
                setlog("服务器接受", "关注");
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(poststr);
                XmlElement root = xml.DocumentElement;


                wx.ToUserName = root.SelectSingleNode("ToUserName").InnerText;
                wx.FromUserName = root.SelectSingleNode("FromUserName").InnerText;
                wx.MsgType = root.SelectSingleNode("MsgType").InnerText;
                if (wx.MsgType.Trim() == "text")
                {
                    wx.Content = root.SelectSingleNode("Content").InnerText;
                }
                if (wx.MsgType.Trim() == "event")
                {
                    wx.EventName = root.SelectSingleNode("Event").InnerText;
                    wx.EventKey = root.SelectSingleNode("EventKey").InnerText;
                }
                if (wx.MsgType.Trim() == "voice")
                {
                    wx.Recognition = root.SelectSingleNode("Recognition").InnerText;
                }
                Cms.BLL.wx_info wxinfo = new Cms.BLL.wx_info();//配置信息
                Cms.Model.wx_info Model = new Cms.Model.wx_info();//配置信息
                Cms.BLL.wx_userinfo userinfo = new Cms.BLL.wx_userinfo();//微信访问列表
                Cms.Model.wx_userinfo muserinfo = new Cms.Model.wx_userinfo();//微信访问列表
                Model = wxinfo.GetModel(1);
                string str = "";
                string openid = wx.FromUserName;

                string Str = GetJson("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Model.AppId + "&secret=" + Model.AppSecret + "");
                //微信回传的数据为Json格式，将Json格式转化成对象  
                OAuth_Token ModelOAuth_Token = wxuser.JSONToObject<OAuth_Token>(Str);
                setlog("添加ModelOAuth_Token", ModelOAuth_Token.access_token);
                string StrTwo = GetJson("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + ModelOAuth_Token.access_token + "&openid=" + openid + "");
                wxuserinfo ModelTwo = wxuser.JSONToObject<wxuserinfo>(StrTwo);
                muserinfo.subscribe = ModelTwo.subscribe;
                muserinfo.openid = ModelTwo.openid;
                muserinfo.nickname = ModelTwo.nickname;
                muserinfo.sex = ModelTwo.sex;
                muserinfo.language = ModelTwo.language;
                muserinfo.city = ModelTwo.city;
                muserinfo.province = ModelTwo.province;
                muserinfo.country = ModelTwo.country;
                muserinfo.headimgurl = ModelTwo.headimgurl;
                muserinfo.subscribe_time = ModelTwo.subscribe_time;
                muserinfo.remark = ModelTwo.remark;
                muserinfo.updatetime = DateTime.Now;
                //str = setinfo("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + Model.access_token + "&openid=" + openid, "", openid);
                //muserinfo = JSONToObject<Cms.Model.wx_userinfo>(str);
                //Cms.Model.wx_userinfo wxs = new Cms.Model.wx_userinfo();

                //wxs.subscribe = muserinfo.subscribe;
                //wxs.openid = muserinfo.openid;
                //wxs.nickname = muserinfo.nickname;
                //wxs.sex = muserinfo.sex;
                //wxs.language = muserinfo.language;
                //wxs.city = muserinfo.city;
                //wxs.province = muserinfo.province;
                //wxs.country = muserinfo.country;
                //wxs.headimgurl = muserinfo.headimgurl;
                //wxs.subscribe_time = muserinfo.subscribe_time;
                //wxs.remark = muserinfo.remark;
                //wxs.updatetime = DateTime.Now;

                HttpCookie cookie = new HttpCookie("user_openid");//创建Cookie
                cookie["openid"] = muserinfo.openid;//保存Cookie 用户手机
                if (!Cms.DBUtility.DbHelperSQL.Exists("select count(1) from wx_userinfo where openid='" + muserinfo.openid + "'"))
                {
                    setlog("添加ModelTwo.openid", ModelTwo.openid);
                    setlog("添加openid", openid);
                    if (muserinfo.openid != "")
                    {
                        setlog("添加", openid);
                        userinfo.Add(muserinfo);
                    }
                    else
                    {
                        DataTable dtUserInfo = new Cms.BLL.wx_userinfo().GetList("openid='" + muserinfo.openid + "' order by updatetime desc").Tables[0];
                        if (dtUserInfo != null && dtUserInfo.Rows.Count > 0)
                        {
                            muserinfo.id = int.Parse(dtUserInfo.Rows[0]["id"].ToString());
                            userinfo.Update(muserinfo);
                        }
                    }

                }
                else
                {
                    DataTable dtUserInfo = new Cms.BLL.wx_userinfo().GetList("openid='" + muserinfo.openid + "' order by updatetime desc").Tables[0];
                    if (dtUserInfo != null && dtUserInfo.Rows.Count > 0)
                    {
                        setlog("更新", openid);
                        muserinfo.id = int.Parse(dtUserInfo.Rows[0]["id"].ToString());
                        userinfo.Update(muserinfo);
                    }

                }

                Cms.BLL.wx_ConcernReply cb = new Cms.BLL.wx_ConcernReply();
                DataTable dt = cb.GetList("isopen=1").Tables[0];
                if (dt.Rows.Count > 0)
                {
                    string type = dt.Rows[0]["typeid"].ToString();
                    if (type == "0")
                    {
                        res = sendTextMessage(wx, dt.Rows[0]["contents"].ToString());
                    }
                    if (type == "1")
                    {
                        res = sendPicTextMessage(wx, dt.Rows[0]["title"].ToString(), dt.Rows[0]["title"].ToString(), dt.Rows[0]["fileurl"].ToString(), dt.Rows[0]["url"].ToString());
                    }
                    if (type == "2")
                    {
                        DateTime time = DateTime.Now;
                        DateTime dttime = Convert.ToDateTime(dt.Rows[0]["updatetime"].ToString());
                        TimeSpan s = time - dttime;
                        int days = s.Days;
                        string fileurl = dt.Rows[0]["fileurl"].ToString();
                        string media_id = dt.Rows[0]["media_id"].ToString();
                        if (days > 2)
                        {

                            media_id = HttpUploadFile(fileurl);
                            if (media_id.Length < 40)
                            {
                                DataTable dts = cb.GetList("typeid=0 order by updatetime desc").Tables[0];
                                if (dts.Rows.Count > 0)
                                {
                                    res = sendTextMessage(wx, dts.Rows[0]["contents"].ToString());
                                }
                            }
                            else
                            {
                                Cms.Model.wx_ConcernReply cmwx = new Cms.Model.wx_ConcernReply();
                                cmwx = cb.GetModel(int.Parse(dt.Rows[0]["id"].ToString()));
                                cmwx.updatetime = time;
                                cmwx.media_id = media_id;
                                cb.Update(cmwx);
                            }
                        }
                        res = sendVoiceMessage(wx, media_id);
                        setlog(res, "语音信息");
                    }
                }
                else
                {
                    res = sendTextMessage(wx, "成功关注");
                }

                wxuser.setstatistics("", "", "", 3, 1);
            }
            #endregion

            #region //取消关注===============================
            if (poststr.IndexOf("unsubscribe") > -1 || poststr.IndexOf("UNSUBSCRIBE") > -1)
            {
                setlog("服务器接受", "取消关注");
                wxuser.setstatistics("", "", "", 4, 1);
            }
            #endregion

            #region //点击事件判断===================================
            if (poststr.IndexOf("CLICK") > -1 || poststr.IndexOf("click") > -1)
            {
                setlog("服务器接受", "CLICK");
                wxmessage wx = new wxmessage();
                wx = GetWxMessage(poststr);
                if (!string.IsNullOrEmpty(wx.EventName) && wx.EventName.Trim() == "CLICK" || wx.EventName.Trim() == "click")
                {

                    Cms.BLL.wx_menu me = new Cms.BLL.wx_menu();
                    DataTable dt = new DataTable();

                    if (wx.EventKey == "map001")
                    {
                        string sinfo = "请按以下步骤发生您当前位置来查看距离您最近的深圳戴维克珠宝首饰专卖店：1.点击键盘按钮切换到输入模式,2.点击“+”号按钮 3.点击“位置”按钮并发生位置";
                        res = sendPicTextMessage(wx, "您附近的深圳戴维克珠宝首饰专卖店", sinfo, "http://anpurui.gotoip4.com/Upload/image/20150120/wxwz.jpg", "");
                    }
                    else
                    {
                        //dt = me.GetList("keys='" + wx.EventKey + "'").Tables[0];
                        //if (dt.Rows.Count > 0)
                        //{
                        //    DataRow dr = dt.Rows[0];
                        //    res = sendTextMessage(wx, dr["info"].ToString());
                        //}
                        Cms.BLL.wx_requestRule rBll = new Cms.BLL.wx_requestRule();
                        int responseType = 0;
                        string modelFunctionName = "";
                        int modelFunctionId = 0;
                        int ruleId = rBll.GetRuleIdByKeyWords(1, wx.EventKey, out responseType, out modelFunctionName, out modelFunctionId);
                        dt = rBll.GetList("reqKeywords='" + wx.EventKey + "'").Tables[0];
                        if (dt.Rows.Count > 0)
                        {
                            responseType = Convert.ToInt32(dt.Rows[0]["responseType"].ToString());
                        }
                        //回复图文的
                        if (responseType == 2)
                        {
                            string openid = wx.FromUserName;
                            string token = ConvertDateTimeInt(DateTime.Now).ToString();
                            List<Article> picTxtList = getDataPicTxtComm(1, ruleId, openid, token);
                            string content = "";
                            for (int i = 0; i < picTxtList.Count; i++)
                            {
                                string str = "<item><Title><![CDATA[{Title}]]></Title><Description><![CDATA[{Description}]]]></Description><PicUrl><![CDATA[{PicUrl}]]></PicUrl><Url><![CDATA[{Url}]]></Url></item>";
                                str = str.Replace("{Title}", picTxtList[i].Title);
                                str = str.Replace("{Description}", picTxtList[i].Description);
                                str = str.Replace("{PicUrl}", picTxtList[i].PicUrl);
                                str = str.Replace("{Url}", picTxtList[i].Url);
                                content += str;
                            }
                            res = sendPicMessage(wx, content.ToString(), picTxtList.Count);
                        }
                        //回复文本的
                        else
                        {
                            Cms.BLL.wx_requestRuleContent rcBll = new Cms.BLL.wx_requestRuleContent();
                            dt = rcBll.GetList("rId=" + ruleId + "").Tables[0];
                            if (dt.Rows.Count > 0)
                            {
                                res = sendTextMessage(wx, dt.Rows[0]["rContent"].ToString());
                            }
                        }
                    }
                }
            }
            #endregion
           
            #region 文本回复============================================
            if (poststr.IndexOf("text") > -1)
            {
                setlog("服务器接受", "text");
                wxmessage wx = new wxmessage();//声明
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(poststr);
                XmlElement root = xml.DocumentElement;
                wx.ToUserName = root.SelectSingleNode("ToUserName").InnerText;
                wx.FromUserName = root.SelectSingleNode("FromUserName").InnerText;
                wx.MsgType = root.SelectSingleNode("MsgType").InnerText;
                if (wx.MsgType.Trim() == "event")
                {
                    wx.EventName = root.SelectSingleNode("Event").InnerText;
                    wx.EventKey = root.SelectSingleNode("EventKey").InnerText;
                }
                if (wx.MsgType.Trim() == "voice")
                {
                    wx.Recognition = root.SelectSingleNode("Recognition").InnerText;
                }
                if (wx.MsgType.Trim() == "text")
                {
                    
                    wx.Content = root.SelectSingleNode("Content").InnerText;
                    Cms.BLL.wx_requestRule rBll = new Cms.BLL.wx_requestRule();
                    int responseType = 0;
                    string modelFunctionName = "";
                    int modelFunctionId = 0;
                    int ruleId = rBll.GetRuleIdByKeyWords(1, wx.Content, out responseType, out modelFunctionName, out modelFunctionId);
                    DataTable dt = rBll.GetList("reqKeywords='" + wx.Content + "'").Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        responseType = Convert.ToInt32(dt.Rows[0]["responseType"].ToString());
                    }
                    //回复图文的
                    if (responseType == 2)
                    {
                        string openid = wx.FromUserName;
                        string token = ConvertDateTimeInt(DateTime.Now).ToString();
                        List<Article> picTxtList = getDataPicTxtComm(1, ruleId, openid, token);
                        string content = "";
                        for (int i = 0; i < picTxtList.Count; i++)
                        {
                            string str = "<item><Title><![CDATA[{Title}]]></Title><Description><![CDATA[{Description}]]]></Description><PicUrl><![CDATA[{PicUrl}]]></PicUrl><Url><![CDATA[{Url}]]></Url></item>";
                            str = str.Replace("{Title}", picTxtList[i].Title);
                            str = str.Replace("{Description}", picTxtList[i].Description);
                            str = str.Replace("{PicUrl}", picTxtList[i].PicUrl);
                            str = str.Replace("{Url}", picTxtList[i].Url);
                            content += str;
                        }
                        res = sendPicMessage(wx, content.ToString(), picTxtList.Count);
                    }
                    //回复文本的
                    else
                    {
                        Cms.BLL.wx_requestRuleContent rcBll = new Cms.BLL.wx_requestRuleContent();
                        dt = rcBll.GetList("rId=" + ruleId + "").Tables[0];
                        if (dt.Rows.Count > 0)
                        {
                            res = sendTextMessage(wx, dt.Rows[0]["rContent"].ToString());
                        }
                    }

                }

            }
            #endregion

            HttpContext.Current.Response.ContentType = "text/xml";
            HttpContext.Current.Response.Write(res);
        }
        catch (Exception ex)
        {
            setlog(ex.Message, "错误1");
        }
    }

    #region 读取图文列表序列化======================
    public List<Article> getDataPicTxtComm(int wid, int Indexid, string openid, string token)
    {
        List<Article> retlist = new List<Article>();
        string website = MyCommFun.getWebSite();

        Cms.BLL.wx_requestRuleContent rcBll = new Cms.BLL.wx_requestRuleContent();

        IList<Cms.Model.wx_requestRuleContent> twList = rcBll.GetTuWenContent(Indexid);


        Article article = new Article();
        for (int i = 0; i < twList.Count(); i++)
        {
            article = new Article();
            article.Title = ProcTitle(twList[i].rContent, openid);
            article.Description = twList[i].rContent2;
            article.Url = getWXApiUrl(twList[i].detailUrl, token, openid) + rcBll.cardnoStr(wid, openid) + getWxUrl_suffix();
            if (twList[i].picUrl == null || twList[i].picUrl.ToString().Trim() == "")
            {
                article.PicUrl = "";
            }
            else
            {
                if (twList[i].picUrl.Contains("http://"))
                {
                    article.PicUrl = twList[i].picUrl;

                }
                else
                {
                    article.PicUrl = website + twList[i].picUrl;
                }
            }
            retlist.Add(article);
        }

        return retlist;

    }
    /// <summary>
    /// 设置微信url地址的后缀
    /// </summary>
    /// <returns></returns>
    public string getWxUrl_suffix()
    {
        string nati_suffix = Utils.GetAppSettingValue("nati_suffix");
        if (nati_suffix == "")
        {
            return "#mp.weixin.qq.com";
        }
        else
        {
            return "&" + nati_suffix;
        }

    }
    public string getWXApiUrl(string url, string token, string openid)
    {

        string ret = "";
        if (url.Contains("?"))
        {
            ret = url + "&token=" + token + "&openid=" + openid;
        }
        else
        {
            ret = url + "?token=" + token + "&openid=" + openid;
        }

        return ret;
    }
    /// <summary>
    /// 如果content包含了sn码，则将sn码动态替换成一个值
    /// [jintian]==当天的日期
    /// [zuotian]==昨天的日期
    /// [mingtian]==明天的日期
    /// </summary>
    /// <param name="title"></param>
    /// <param name="openid"></param>
    /// <returns></returns>
    private string ProcTitle(string content, string openid)
    {
        //if (content.Contains("[sn]"))
        //{
        //    MxWeiXin.BLL.wx_sn_info snBll = new MxWeiXin.BLL.wx_sn_info();
        //    content = content.Replace("[sn]", snBll.getNewRadmInfo(openid));
        //}
        content = content.Replace("[jintian]", DateTime.Now.ToString("yyyy年MM月dd日"));
        content = content.Replace("[zuotian]", DateTime.Now.AddDays(-1).ToString("yyyy年MM月dd日"));
        content = content.Replace("[mingtian]", DateTime.Now.AddDays(1).ToString("yyyy年MM月dd日"));
        return content;
    }


    #endregion

    private wxmessage GetWxMessage(string poststr)
    {
        wxmessage wx = new wxmessage();
        try
        {
            XElement lkfroot = null;
            XDocument xdoc = XDocument.Parse(poststr); lkfroot = xdoc.Root;

            wx.ToUserName = lkfroot.Element("ToUserName").Value;
            wx.FromUserName = lkfroot.Element("FromUserName").Value;
            wx.MsgType = lkfroot.Element("MsgType").Value;
            if (wx.MsgType.Trim() == "text")
            {
                wx.Content = lkfroot.Element("Content").Value;
            }
            if (wx.MsgType.Trim() == "event")
            {

                wx.EventName = lkfroot.Element("Event").Value;
                wx.EventKey = lkfroot.Element("EventKey").Value;
            }
            if (wx.MsgType.Trim() == "voice")
            {
                wx.Recognition = lkfroot.Element("Recognition").Value;
            }

            //wx.ToUserName = xml.SelectSingleNode("xml").SelectSingleNode("ToUserName").InnerText;
            //wx.FromUserName = xml.SelectSingleNode("xml").SelectSingleNode("FromUserName").InnerText;
            //wx.MsgType = xml.SelectSingleNode("xml").SelectSingleNode("MsgType").InnerText;
            //if (wx.MsgType.Trim() == "text")
            //{
            //    wx.Content = xml.SelectSingleNode("xml").SelectSingleNode("Content").InnerText;
            //}
            //if (wx.MsgType.Trim() == "event")
            //{

            //    wx.EventName = xml.SelectSingleNode("xml").SelectSingleNode("Event").InnerText;
            //    wx.EventKey = xml.SelectSingleNode("xml").SelectSingleNode("EventKey").InnerText;
            //}
            //if (wx.MsgType.Trim() == "voice")
            //{
            //    wx.Recognition = xml.SelectSingleNode("xml").SelectSingleNode("Recognition").InnerText;
            //}
            // writelog(wx.MsgType.Trim());
        }
        catch (Exception ex)
        {
            //  writelog(ex.Message+"2");
            setlog(ex.Message, "错误2");
        }
        return wx;
    }
    #endregion

    /// <summary>
    /// 接受信息
    /// </summary>
    /// <param name="url">目标连接地址</param>
    /// <returns></returns>
    protected static string GetJson(string url)
    {
        WebClient wc = new WebClient();
        wc.Credentials = CredentialCache.DefaultCredentials;
        wc.Encoding = Encoding.UTF8;
        string returnText = wc.DownloadString(url);
        if (returnText.Contains("errcode"))
        {
            //可能发生错误  
        }
        return returnText;
    }
    public class OAuth_Token
    {
        public OAuth_Token()
        {
            //  
            //TODO: 在此处添加构造函数逻辑  
            //  
        }
        //access_token 网页授权接口调用凭证,注意：此access_token与基础支持的access_token不同  
        //expires_in access_token接口调用凭证超时时间，单位（秒）  
        //refresh_token 用户刷新access_token  
        //openid 用户唯一标识，请注意，在未关注公众号时，用户访问公众号的网页，也会产生一个用户和公众号唯一的OpenID  
        //scope 用户授权的作用域，使用逗号（,）分隔  
        public string _access_token;
        public string _expires_in;
        public string _refresh_token;
        public string _openid;
        public string _scope;
        public string access_token
        {
            set { _access_token = value; }
            get { return _access_token; }
        }
        public string expires_in
        {
            set { _expires_in = value; }
            get { return _expires_in; }
        }
        public string refresh_token
        {
            set { _refresh_token = value; }
            get { return _refresh_token; }
        }
        public string openid
        {
            set { _openid = value; }
            get { return _openid; }
        }
        public string scope
        {
            set { _scope = value; }
            get { return _scope; }
        }
    }  
    #region 计算地理位置距离=================================
    static double DEF_PI = 3.14159265359; // PI
    static double DEF_2PI = 6.28318530712; // 2*PI
    static double DEF_PI180 = 0.01745329252; // PI/180.0
    static double DEF_R = 6370693.5; // radius of earth

    public static double getcalculate(double mLat1, double mLon1, double mLat2, double mLon2)
    {
        double calculate;
        try
        {
            //  wxuser.setstatistics("", "微信消息ss", mLat1.ToString() + mLon1.ToString(), 0, 1);
            calculate = GetShortDistance(mLon1, mLat1, mLon2, mLat2);

            if (calculate > double.Parse("1000"))
            {
                calculate = 0;
            }
        }
        catch
        {
            calculate = 1;
        }
        return calculate;
    }
    public static double GetShortDistance(double lon1, double lat1, double lon2, double lat2)
    {
        double ew1, ns1, ew2, ns2;
        double dx, dy, dew;
        double distance;
        // 角度转换为弧度
        ew1 = lon1 * DEF_PI180;
        ns1 = lat1 * DEF_PI180;
        ew2 = lon2 * DEF_PI180;
        ns2 = lat2 * DEF_PI180;
        // 经度差
        dew = ew1 - ew2;
        // 若跨东经和西经180 度，进行调整
        if (dew > DEF_PI)
            dew = DEF_2PI - dew;
        else if (dew < -DEF_PI)
            dew = DEF_2PI + dew;
        dx = DEF_R * Math.Cos(ns1) * dew; // 东西方向长度(在纬度圈上的投影长度)
        dy = DEF_R * (ns1 - ns2); // 南北方向长度(在经度圈上的投影长度)
        // 勾股定理求斜边长
        distance = Math.Sqrt(dx * dx + dy * dy);
        return distance;
    }
    #endregion

    #region 配置服务器
    //配置服务器
    public void InterfaceTest()
    {
        string token = "c21bba9c6036dd8fb";
        if (string.IsNullOrEmpty(token))
        {
            return;
        }

        string echoString = HttpContext.Current.Request.QueryString["echostr"];
        string signature = HttpContext.Current.Request.QueryString["signature"];
        string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
        string nonce = HttpContext.Current.Request.QueryString["nonce"];
        if (!string.IsNullOrEmpty(echoString))
        {
            HttpContext.Current.Response.Write(echoString);
            HttpContext.Current.Response.End();
        }

    }
    #endregion

    #region 发送内容格式  上传文件   获取会员信息
    /// <summary>    
    ///发送文本信息   
    /// </summary>    
    /// <param name="wx">接受信息</param>    
    /// <param name="content">发送内容</param>    
    /// <returns></returns>    
    private string sendTextMessage(wxmessage wx, string content)
    {


        string res = string.Format(@"<xml>  
                                <ToUserName><![CDATA[{0}]]></ToUserName>  
                                <FromUserName><![CDATA[{1}]]></FromUserName>  
                                <CreateTime>{2}</CreateTime>  
                                <MsgType><![CDATA[text]]></MsgType>  
                                <Content><![CDATA[{3}]]></Content>  
                                </xml> ",
                    wx.FromUserName, wx.ToUserName, ConvertDateTimeInt(DateTime.Now), content);

        return res;
    }

    /// <summary>    
    ///发送图片信息   
    /// </summary>    
    /// <param name="_mode">接受信息</param>    
    /// <param name="title">标题</param>   
    ///  <param name="description">描述</param>  
    ///   <param name="picurl">图片路径</param>  
    ///    <param name="url">图片指向路径</param>  
    /// <returns></returns>  
    protected string sendPicTextMessage(wxmessage _mode, string title, string description, string picurl, string url)
    {

        string res = string.Format(@"<xml>  
                                        <ToUserName><![CDATA[{0}]]></ToUserName>  
                                        <FromUserName><![CDATA[{1}]]></FromUserName>  
                                        <CreateTime>{2}</CreateTime>  
                                        <MsgType><![CDATA[news]]></MsgType>  
                                        <ArticleCount>1</ArticleCount>  
                                        <Articles>  
                                        <item>  
                                        <Title><![CDATA[{3}]]></Title>   
                                        <Description><![CDATA[{4}]]></Description>  
                                        <PicUrl><![CDATA[{5}]]></PicUrl>  
                                        <Url><![CDATA[{6}]]></Url>  
                                        </item>  
                                        </Articles>  
                                </xml> ",
        _mode.FromUserName, _mode.ToUserName, ConvertDateTimeInt(DateTime.Now), title, description, picurl, url);

        return res;

    }

    /// <summary>    
    ///发送语音文件   
    /// </summary>    
    /// <param name="_mode">接受信息</param>    
    /// <param name="MediaId">语音文件ID</param>    
    /// <returns></returns>    
    protected string sendVoiceMessage(wxmessage _mode, string MediaId)
    {

        string res = string.Format(@"<xml>  
                                        <ToUserName><![CDATA[{0}]]></ToUserName>  
                                        <FromUserName><![CDATA[{1}]]></FromUserName>  
                                        <CreateTime>{2}</CreateTime>  
                                        <MsgType><![CDATA[voice]]></MsgType>  
                                        <Voice>  
                                        <MediaId><![CDATA[{3}]]></MediaId>                              
                                        </Voice>  
                                </xml> ",
        _mode.FromUserName, _mode.ToUserName, ConvertDateTimeInt(DateTime.Now), MediaId);

        return res;

    }

    /// <summary>    
    ///发送图文列表   
    /// </summary>    
    /// <param name="_mode">接受信息</param>    
    /// <param name="str">图文内容</param>  
    /// <param name="Count">图文数量</param> 
    /// <returns></returns> 
    protected string sendPicMessage(wxmessage _mode, string str, int Count)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<xml> ");
        sb.Append("<ToUserName><![CDATA[" + _mode.FromUserName + "]]></ToUserName> ");
        sb.Append("<FromUserName><![CDATA[" + _mode.ToUserName + "]]></FromUserName>");
        sb.Append("<CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime>");
        sb.Append("<MsgType><![CDATA[news]]></MsgType>");
        sb.Append("<ArticleCount>" + Count + "</ArticleCount>");
        sb.Append("<Articles>");
        sb.Append(str);
        sb.Append("</Articles>");
        sb.Append("</xml> ");
        return sb.ToString();
    }


    /// <summary>    
    ///取得当前时间编码   
    /// </summary>   
    public int ConvertDateTimeInt(System.DateTime time)
    {
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
        return (int)(time - startTime).TotalSeconds;
    }

    /// <summary>    
    ///上传语音   
    /// </summary> 
    public string HttpUploadFile(string postData)
    {
        Cms.BLL.wx_info wxinfo = new Cms.BLL.wx_info();
        Cms.Model.wx_info Model = new Cms.Model.wx_info();
        Model = wxinfo.GetModel(1);
        string result = "";
        string posturl = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + Model.access_token + "&type=voice";

        string filepath = Server.MapPath("~" + postData);

        WebClient myWebClient = new WebClient();
        myWebClient.Credentials = CredentialCache.DefaultCredentials;
        try
        {
            byte[] responseArray = myWebClient.UploadFile(posturl, "POST", filepath);
            result = System.Text.Encoding.Default.GetString(responseArray, 0, responseArray.Length);

            if (result.IndexOf("42001") > -1)
            {
                string str = Gettoken();
                Cms.BLL.wx_info wx = new Cms.BLL.wx_info();
                Cms.Model.wx_info mwx = new Cms.Model.wx_info();
                mwx = wx.GetModel(1);
                mwx.access_token = str;
                wx.Update(mwx);

                HttpUploadFile(postData);


            }

            string s = result.Replace("{", "").Replace("}", "").Replace("\"", "");
            string[] ss = s.Split(',');
            result = ss[1].Replace("media_id:", "");
        }
        catch (Exception ex)
        {
            result = "Error:" + ex.Message;
        }

        return result;

    }


    /// <summary>    
    ///上传语音   
    /// </summary> 
    public static string setinfo(string posturl, string postData, string openid)
    {
        Stream outstream = null;
        Stream instream = null;
        StreamReader sr = null;
        HttpWebResponse response = null;
        HttpWebRequest request = null;
        Encoding encoding = Encoding.UTF8;
        byte[] data = encoding.GetBytes(postData);
        // 准备请求...
        try
        {
            // 设置参数
            request = WebRequest.Create(posturl) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            outstream = request.GetRequestStream();
            outstream.Write(data, 0, data.Length);
            outstream.Close();
            //发送请求并获取相应回应数据
            response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            instream = response.GetResponseStream();
            sr = new StreamReader(instream, encoding);
            //返回结果网页（html）代码
            string content = sr.ReadToEnd();
            string err = string.Empty;

            if (content.IndexOf("42001") > -1)
            {
                string str = Gettoken();
                Cms.BLL.wx_info wx = new Cms.BLL.wx_info();
                Cms.Model.wx_info mwx = new Cms.Model.wx_info();
                mwx = wx.GetModel(1);
                mwx.access_token = str;
                wx.Update(mwx);

                setinfo("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + str + "&openid=" + openid, postData, openid);


            }
            return content;
        }
        catch (Exception ex)
        {
            string err = ex.Message;
            return string.Empty;
        }
    }

    #region ///获取token   ===================

    /// <summary>    
    ///获取token   
    /// </summary> 
    public static string Gettoken()
    {
        Cms.BLL.wx_info wxinfo = new Cms.BLL.wx_info();
        Cms.Model.wx_info Model = new Cms.Model.wx_info();
        Model = wxinfo.GetModel(1);


        string sAppId = Model.AppId;
        string sAppSecret = Model.AppSecret;
        string posturl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + sAppId + "&secret=" + sAppSecret + "";
        string postData = "";

        //Stream outstream = null;
        Stream instream = null;
        StreamReader sr = null;
        HttpWebResponse response = null;
        HttpWebRequest request = null;
        Encoding encoding = Encoding.UTF8;
        byte[] data = encoding.GetBytes(postData);
        // 准备请求...
        try
        {
            request = WebRequest.Create(posturl) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            //发送请求并获取相应回应数据
            response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            instream = response.GetResponseStream();
            sr = new StreamReader(instream, encoding);
            //返回结果网页（html）代码
            string content = sr.ReadToEnd();
            string err = string.Empty;

            string[] s = content.Split(',');
            string str = s[0].Replace("access_token", "").Replace(":", "").Replace("{", "").Replace("\"", "");
            //Response.Write(content);
            return str;
        }
        catch (Exception ex)
        {
            string err = ex.Message;
            return string.Empty;
        }
    }

    #endregion

    #region JSON转换  =================
    /// <summary>    
    ///JSON转换  
    /// </summary> 
    public static T JSONToObject<T>(string jsonText)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        try
        {
            return jss.Deserialize<T>(jsonText);
        }
        catch (Exception ex)
        {
            throw new Exception("JSONHelper.JSONToObject(): " + ex.Message);
        }
    }
    #endregion

    #endregion
}